<template>
  <div>
    <el-dialog
      :close-on-click-modal="false"
      v-model="visibleDialog"
      :title="props.title"
      width="600px"
      draggable
      @close="closeDialog"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="130px"
        style="width: 90%"
        label-position="right"
      >
        <el-form-item label="创建方式" prop="enabled" v-if="!formData.id">
          <el-radio-group v-model="formData.enabled">
            <el-radio-button label="0">新建工作台</el-radio-button>
            <el-radio-button label="1">使用模板</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          v-if="formData.enabled === '1' && !formData.id"
          label="选择模板"
          prop="workbenchTemplateId"
        >
          <el-select
            v-model="formData.workbenchTemplateId"
            placeholder="请选择工作台模板"
            style="width: 100%"
          >
            <el-option
              v-for="item in templateList"
              :key="item.id"
              :label="item.workbenchName"
              :value="item.id"
              :disabled="props.isReadonly"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="工作台编号" prop="workbenchCode">
          <el-input
            v-if="!props.isReadonly"
            v-model="formData.workbenchCode"
            placeholder="请输入工作台编号"
            clearable
          />

          <span v-else>{{ formData.workbenchCode }}</span>
        </el-form-item>
        <el-form-item label="工作台名称" prop="workbenchName">
          <el-input
            v-if="!props.isReadonly"
            v-model="formData.workbenchName"
            placeholder="请输入工作台名称"
            clearable
          />

          <span v-else>{{ formData.workbenchName }}</span>
        </el-form-item>
        <el-form-item label="工作台类型" prop="workbenchType">
          <el-select v-model="formData.workbenchType">
            <el-option
              v-for="item in dictionaryStore.filterDictList('WorkbenchType')"
              :key="item.value"
              :label="item.label"
              :value="item.value"
              :disabled="props.isReadonly"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="公共模板" prop="isPublic">
          <el-switch v-model="formData.isPublic" :disabled="props.isReadonly" />
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input
            v-if="!props.isReadonly"
            v-model="formData.remarks"
            placeholder="请输入备注"
            type="textarea"
            show-word-limit
            :maxlength="250"
            :autosize="{ minRows: 3, maxRows: 4 }"
            clearable
          />

          <span v-else>{{ formData.remarks || "无" }}</span>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            v-if="!props.isReadonly"
            type="primary"
            :loading="loading"
            @click="handleSubmit"
            >确 定</el-button
          >
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary";
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "SysworkbenchinfoEdit",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  belongUserId: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    if (newVal) {
      getTemplateList();
    }
  }
);

const rules = reactive({
  enabled: [
    {
      required: true,
      message: "请选择工作台状态",
      trigger: "change",
    },
  ],
  workbenchTemplateId: [
    {
      required: true,
      message: "请选择工作台模板",
      trigger: "blur",
    },
  ],
  workbenchCode: [
    { required: true, message: "请填写工作台编号", trigger: "blur" },
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
  workbenchName: [
    { required: true, message: "请填写工作台名称", trigger: "blur" },
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
  workbenchType: [
    {
      required: true,
      message: "请选择工作台类型",
      trigger: "blur",
    },
    { min: 1, max: 20, message: "长度在 1 到 20 个字符", trigger: "blur" },
  ],
  remarks: [
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
});

const formRef = ref(ElForm);

let formData: any = reactive({
  id: "",
  version: "",
  workbenchCode: "",
  workbenchName: "",
  workbenchType:
    dictionaryStore.filterDictList("WorkbenchType")[0]?.value || "",
  isPublic: false,
  backgroundImageId: "",
  backgroundImageUrl: "",
  remarks: "",
  deleted: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  enabled: "0",
  workbenchTemplateId: "",
});

watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      const {
        id,
        version,
        workbenchCode,
        workbenchName,
        workbenchType,
        isPublic,
        backgroundImageId,
        backgroundImageUrl,
        remarks,
        deleted,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        belongUserId,
      } = newVal;
      Object.assign(formData, {
        id,
        version,
        workbenchCode,
        workbenchName,
        workbenchType,
        isPublic: isPublic === 1 ? true : false,
        backgroundImageId,
        backgroundImageUrl,
        remarks,
        deleted,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        belongUserId,
      });
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.id = "";
  formData.version = "";
  formData.workbenchCode = "";
  formData.workbenchName = "";
  formData.workbenchType =
    dictionaryStore.filterDictList("WorkbenchType")[0]?.value || "";
  formData.isPublic = false;
  formData.backgroundImageId = "";
  formData.backgroundImageUrl = "";
  formData.remarks = "";
  formData.deleted = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.belongUserId = props.belongUserId;
  // formData.workbenchTemplateId = "";
}

const loading = ref(false);

/** 工作台信息保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      formData.isPublic = formData.isPublic ? 1 : 0;
      formData.belongUserId = props.belongUserId;
      if (formData.enabled === "1") {
        await request({
          url: `/system/sysworkbenchinfo/createByTemplate/${formData.workbenchTemplateId}`,
          method: "post",
          data: formData,
        }).finally(() => {
          loading.value = false;
        });
      } else {
        await request({
          url: "/system/sysworkbenchinfo/save",
          method: "post",
          data: formData,
        }).finally(() => {
          loading.value = false;
        });
      }
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}

// 获取模板列表
const templateList: any = ref([]);
async function getTemplateList() {
  const data = await request({
    url: "/system/sysworkbenchinfo/getTemplateList",
    method: "get",
  });
  templateList.value = data.data || [];
}

// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});
</script>
